<template>
  <div>
    <a-spin :spinning="loading">
      <div class="operate-page-content route-chart-container">
        <div class="header-search">
          <a-row :gutter="40" class="flex align-center">
            <a-col :span="5">
              {{$t('hangManage.makeNo')}}：
              <span class="text-gray1 ml-10 break-all">{{moInfo.moNo}} </span>
            </a-col>
            <a-col :span="5">
              {{$t('basicData.styleNo')}}：
              <span class="text-gray1 ml-10">{{moInfo.styleNo}} </span>
            </a-col>
            <a-col :span="5">
              {{$t('basicData.styleNa') }}：
              <span class="text-gray1 ml-10">{{moInfo.styleName}} </span>
            </a-col>
            <a-col :span="9" class="text-right">
              <a-select :placeholder="$t('other.selectVersion')" class="text-left" v-model:value="roueteVersionId" v-if="operateType != 'add'" :disabled="operateType == 'edit'">
                <a-select-option v-for="(item, index) in versionList" :key="index" :value="item.id">{{item.name}}</a-select-option>
              </a-select>
              <span v-if="!isEnvOnline">
                <a-button type="primary" class="mr-10 ml-20" :disabled="!versionList.length" v-if="operateType == 'view'" @click="processAdd(2)">{{ $t('common.editor') }}</a-button>
                <a-button type="primary" @click="processAdd(1)" v-if="operateType == 'view'">{{ $t('other.addVersion') }}</a-button>
              </span>
            </a-col>
          </a-row>
        </div>
        <section>
          <roadmapList ref="roadmapListRef" :roueteVersionId="roueteVersionId" :moInfo="moInfo" :staffList="staffList" />
        </section>
      </div>
      <div class="operate-page-btns">
        <a-button class="cancel" v-if="operateType=='view'" @click="closeTab('back')">{{ $t('other.back') }}</a-button>
        <a-space v-else>
          <a-button class="cancel" @click="closeTab('cancel')">{{$t('common.cancel')}}</a-button>
          <a-button type="primary" class="confirm" @click="onConfirm(false)">{{$t('common.ok')}}</a-button>
          <a-button type="primary" class="confirm" @click="onConfirm(true)">{{ $t('other.confirmAddSch') }}</a-button>
        </a-space>
      </div>
    </a-spin>
  </div>
</template>
<script setup>
import { ref, onMounted, computed } from 'vue'
import roadmapList from './roadmapList'
import { useRoute, useRouter } from 'vue-router'
import { message } from 'ant-design-vue'
import axios from "@/utils/request"
import { store } from "@/store";
import { cloneDeep } from 'lodash'
import i18n from '@/locales/index' 
const { t } = i18n.global
const tabs = computed(() => {
  return store.state.setting.tabs
})
let isEnvOnline = ref(process.env.VUE_APP_CONFIG == 'online')
const loading = ref(false)
let router = useRouter()
let route = useRoute()
let moId = ref(null)  // 制单id
let moInfo = ref({})
let roueteVersionId = ref(null)
let versionList = ref([]) // 工艺路线图版本列表
let roadmapListRef = ref()
let operateType = ref('view')
let staffList = ref([])

const getMakeInfo = async (id) => { // 制单信息
  try {
    const res = await axios.getAction('/api/mo/mo/get', { id })
    moInfo.value = res.data || {}
  } catch {
    message.warning(t('components.getDataErrorPleaseHolder'))
    moInfo.value = {}
  }
}
const getStaff = async () => { // 员工
  try {
    const resStaff = await axios.postAction('/api/basic/staff/list')
    console.log(resStaff)
    if (resStaff.success) staffList.value = resStaff.data || []
  } catch {
    message.warning(t('components.getDataErrorPleaseHolder'))
    staffList.value = []
  }
}

const getRouteList = async (id) => {
  try {
    const res = await axios.postAction('/api/mo/mo-proc-roadmap/list', { moId: id })
    if (res.success) {
      versionList.value = res.data || []
      if (res.data.length && !route.query.routeId) roueteVersionId.value = res.data[0].id
    }
  } catch {
    message.warning(t('components.getDataErrorPleaseHolder'))
    versionList.value = []
    roueteVersionId.value = null
  }
}
const queryTableParams = (tableList) => {
  let hangerLineList = []
  tableList.forEach((item, index) => {
    item.sort = item.sort || index + 1
    item.forwardIntegration = item.forwardMerge ? 1 : 0
    item.enable = item.effect ? 1 : 0
    item.moId = item.moId || moId.value
    item.moProcRoadmapProcStationList.forEach((el, i) => {
      el.sort = i + 1
      el.mainAuxiliaryStation = el.mainStationBoolean ? 2 : 1
      el.moId = el.moId || moId.value
      hangerLineList.push(el.hangerLineId)
    })
  })
  return {
    tableList,
    hangerLineList: Array.from(new Set(hangerLineList))
  }
}
const queryParams = () => {
  let { formState, tableList, processId } = roadmapListRef.value
  let params = Object.assign({}, formState)
  let tableData = queryTableParams(cloneDeep(tableList))
  params.moProcRoadmapProcList = tableData.tableList
  params.hangerLineIdList = tableData.hangerLineList
  params.moId = moId.value
  params.processId = processId
  if (operateType.value == 'edit') params.id = roueteVersionId.value
  return params
}
const onConfirm = async (goWipInfo) => {
  try {
    loading.value = true
    await roadmapListRef.value.formRef.validateFields()
    let params = queryParams()
    let url = operateType.value == 'edit' ? '/api/mo/mo-proc-roadmap/edit' : '/api/mo/mo-proc-roadmap/save'
    const res = await axios.postAction(url, params)
    if (res.success) {
      message.success(res.msg || t('common.doSuccess'))
      loading.value = false
      await closeTab('confirm', goWipInfo, { moId: route.query.id, routeId: res.data })
    }
    loading.value = false
  } catch {
    loading.value = false
  }

}
const refreshTab = async (isAdd) => {
  let path = isAdd ? '/makeManage/routeChart/add' : '/makeManage/routeChart/edit'
  const tabList = cloneDeep(tabs.value)
  let changeTabs = tabList.filter((i) => ![path].includes(i.path))
  await store.commit('updateState', { tabs: changeTabs })
}
const processAdd = async (values) => {
  await refreshTab(values == 1)
  router.push(values == 1 ? {
    path: '/makeManage/routeChart/add',
    query: { id: moId.value }
  } : {
    path: '/makeManage/routeChart/edit',
    query: { id: moId.value, routeId: roueteVersionId.value }
  })
}
const closeTab = async (type, goWipInfo, wipInfo) => {
  const tabList = cloneDeep(tabs.value)
  let changeTabs = tabList.filter((i) => {
    if (type == 'confirm') {
      return !['/makeManage/routeChart/details', route.path].includes(i.path)
    } else {
      return i.path !== route.path
    }
  })
  await store.commit('updateState', { tabs: changeTabs })
  if (goWipInfo) {
    await router.replace({ path: '/hangManage/wipInfo/add', query: wipInfo })
  } else {
    type != 'back' ? await router.replace({ path: '/makeManage/routeChart/details', query: { id: moId.value } }) : await router.replace({ path: '/makeManage/routeChart' })
  }
}
onMounted(async () => {
  loading.value = true
  try {
    moId.value = route.query.id
    operateType.value = route.path == '/makeManage/routeChart/add' ? 'add' : route.path == '/makeManage/routeChart/edit' ? 'edit' : 'view'
    if (route.query.routeId) roueteVersionId.value = route.query.routeId
    await getStaff()
    await getMakeInfo(moId.value)
    await getRouteList(moId.value)
    loading.value = false
  } catch {
    loading.value = false
  }
})
</script>